#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Filename: testing_meeting.py
# Author: ChenChangSong
# Date: 2025-08-24 10:30:00

"""
功能描述: 工作汇总
"""
# 使用相对路径导入
# 添加相对路径以便导入comm模块
import os
import sys
from pathlib import Path
sys.path.append(str(Path(__file__).resolve().parent.parent.parent))

from math import log
import requests
import json
import copy

# 明确导入需要的内容
from comm.common_code import logger, log_to_ui_info, log_to_ui_error, api_request,get_excel_data

def testing_meeting(name_value,time_value):
    """工作汇总"""


    all_data = ''
    get_requirement_list_data,tested_or_testing_req = get_requirement_list(name_value,time_value)
    get_fixed_bug_list_data = get_fixed_bug_list(name_value,time_value)

    # 所有数据：需求+bug
    all_data += get_requirement_list_data
    all_data += get_fixed_bug_list_data
    all_data += tested_or_testing_req

    logger.info(f"您输入的姓名{name_value}，上周时间{time_value}")
    log_to_ui_info(f"您输入的姓名{name_value}，上周时间{time_value}")
    logger.info(all_data)
    log_to_ui_info(all_data)

def get_requirement_list(name_value,time_value):
    """需求列表"""
    excel_data = get_excel_data()
    url = "https://www.tapd.cn/api/entity/stories/stories_list"
    # 定义payload字典
    payload = {
    "exclude_workspace_configs": [],
    "workspace_id": f"{excel_data['项目ID']}",
    "category_id": "0",
    "list_type": "tree",
    "conf_id": f"11{excel_data['项目ID']}001129840",
    "confIdType": "URL",
    "sort_name": "sort",
    "order": "",
    "perpage": 100,
    "page": 1,
    "need_category_counts": 1,
    "entity_types": [
        "story"
    ],
    "selected_workspace_ids": [
        f"{excel_data['项目ID']}"
    ],
    "location": "/prong/stories/stories_list",
    "menu_workitem_type_id": "",
    "identifier": "app_for_list_tools,app_for_list_operation",
    "hide_not_match_condition_sub_node": 1,
    "block_type": "",
    "block_size": 20,
    "primary_data_only": False,
    "app_id": "",
    "useScene": "storyList",
    "filter_data": {
        "filter_expr": {
        "data": [
            {
            "fieldOption": "in",
            "fieldType": "user_chooser",
            "entity": "story",
            "fieldSubValue": "",
            "fieldSystemName": "测试人员",
            "fieldDisplayName": "测试人员",
            "selectOption": [],
            "value": f"{name_value};",
            "fieldIsSystem": "0"
            }
        ],
        "optionType": "AND",
        "needInit": True
        },
        "filter_type": "base"
    },
    "dsc_token": "ZYJtvBRTRbQCNOMH"
    }
    payload_time = copy.deepcopy(payload)
    payload_testing = copy.deepcopy(payload)
    payload_tested_or_testing = copy.deepcopy(payload)

    # 将字典转换为JSON字符串用于请求
    headers = {
    'Accept': 'application/json, text/plain, */*',
    'Accept-Language': 'zh-CN,zh;q=0.9',
    'Cache-Control': 'no-cache',
    'Connection': 'keep-alive',
    'Content-Type': 'application/json',
    'Cookie': excel_data['Cookie'],
    'Origin': 'https://www.tapd.cn',
    'Pragma': 'no-cache',
    # 'Referer': f'https://www.tapd.cn/tapd_fe/{excel_data['项目ID']}/story/list?categoryId=0&amp%3Bsort_name=status&amp%3Border=asc&amp%3BuseScene=storyList&amp%3BgroupType=&amp%3Bconf_id=1166606973001129840&amp%3BqueryToken=d66e9e50b42075431ef3670d96a2b8f9&amp%3Bpage=1&sort_name=sort&useScene=storyList&groupType=&conf_id=1166606973001129840&queryToken=08b68dc74588ed777704f551ef7d4b47&page=1',
    'Sec-Fetch-Dest': 'empty',
    'Sec-Fetch-Mode': 'cors',
    'Sec-Fetch-Site': 'same-origin',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.5845.97 Safari/537.36 Core/1.116.559.400 QQBrowser/19.6.6683.400',
    'sec-ch-ua': '"Not)A;Brand";v="24", "Chromium";v="116"',
    'sec-ch-ua-mobile': '?0',
    'sec-ch-ua-platform': '"Windows"'
    }

    # 上周测试任务
    last_week_testing_task='上周测试任务:\n需求：\n'
    task_count = 0  # 初始化任务计数器

    # 1、已发布需求==============================================
    payload_release_time={
          "fieldOption": "between",
          "fieldType": "dateinput",
          "entity": "story",
          "fieldSubValue": "",
          "fieldSystemName": "需求实际发版时间",
          "fieldDisplayName": "需求实际发版时间",
          "selectOption": [],
          "value": f"{time_value}",
          "fieldIsSystem": "0"
        }

    payload_time["filter_data"]["filter_expr"]["data"].append(payload_release_time)  
    respose_code,response = api_request(method="POST", url=url, headers=headers, data=json.dumps(payload_time))
    if respose_code == 200 and response["data"]["stories_list"] != []:
        try:
            stories_list = response["data"]["stories_list"]
            logger.info(f"已发布的需求：{stories_list}")
            for story in stories_list:
                story_name = story["Story"]["name"]
                task_count += 1
                last_week_testing_task += f"\t{task_count}. {story_name}（已上线）\n"
        except:
            logger.error("获取数据失败")
            log_to_ui_error("获取数据失败")
    elif respose_code == 200 and response["data"]["stories_list"] == []:
        logger.info(f"{time_value}没有上线的的需求")
        log_to_ui_info(f"{time_value}没有上线的的需求")
    elif respose_code != 200:
        logger.error("获取已发布的需求失败")
        log_to_ui_error("获取已发布的需求失败")

        
    # 2、测试中的需求==============================================
    payload_test_status ={
            "fieldOption": "in",
            "fieldType": "multi_select",
            "entity": "story",
            "fieldSubValue": "",
            "fieldSystemName": "status",
            "fieldDisplayName": "状态",
            "selectOption": [],
            "value": [
                "待测试",
                "内部测试中",
                "内测完成",
                "本地验收完成"
            ],
            "fieldIsSystem": "1"
            } 
    payload_testing["filter_data"]["filter_expr"]["data"].append(payload_test_status)  
    respose_code,response = api_request(method="POST", url=url, headers=headers, data=json.dumps(payload_testing))
    if respose_code == 200 and response["data"]["stories_list"] != []:
        try:
            stories_list = response["data"]["stories_list"]
            logger.info(f"测试中的需求：{stories_list}")
            for story in stories_list:
                story_name = story["Story"]["name"]
                task_count += 1
                last_week_testing_task += f"\t{task_count}. {story_name}（测试中，进度？%）\n"
        except:
            logger.error("获取数据失败")
            log_to_ui_error("获取数据失败")
    elif respose_code == 200 and response["data"]["stories_list"] == []:
        logger.info(f"没有测试中的需求")
        log_to_ui_info(f"没有测试中的需求")
    elif respose_code != 200:
        logger.error("获取测试中的需求失败")
        log_to_ui_error("获取测试中的需求失败")


       
    # 3、已转测需求或即将转测需求==============================================
    payload_test_status ={
            "fieldOption": "in",
            "fieldType": "multi_select",
            "entity": "story",
            "fieldSubValue": "",
            "fieldSystemName": "status",
            "fieldDisplayName": "状态",
            "selectOption": [],
            "value": [
                "规划中",
                "待技术评审",
                "待需求评审",
                "待开发",
                "开发中",
                "开发自测",
                "开发转产品验收",
                "开发转产品初验",
                "本地验收完成",
                "待测试",
                "测试打回",
                "内部测试中",
                "内测完成",
                "测试转产品验收"

            ],
            "fieldIsSystem": "1"
            } 
    payload_tested_or_testing["filter_data"]["filter_expr"]["data"].append(payload_test_status)  
    respose_code,response = api_request(method="POST", url=url, headers=headers, data=json.dumps(payload_tested_or_testing))
    tested_or_testing_req='已转测或即将转测需求:\n'
    if respose_code == 200 and response["data"]["stories_list"] != []:
        try:
            stories_list = response["data"]["stories_list"]
            logger.info(f"已转测需求或即将转测需求：{stories_list}")
            for index,story in enumerate(stories_list):
                story_name = story["Story"]["name"]
                story_id = story["Story"]["id"]
                tested_or_testing_req += f"\t{index+1}、【 {story_name}】(目前？)\n"
                req_URL = f"https://www.tapd.cn/tapd_fe/{excel_data['项目ID']}/story/detail/{story_id}"
                tested_or_testing_req += f"\t{req_URL}\n"
        except:
            logger.error("获取已转测需求或即将转测需求失败")
            log_to_ui_error("获取已转测需求或即将转测需求失败")
    elif respose_code == 200 and response["data"]["stories_list"] == []:
        logger.info(f"没有已转测需求或即将转测需求")
        log_to_ui_info(f"没有已转测需求或即将转测需求")
    elif respose_code != 200:
        logger.error("获取已转测需求或即将转测需求失败")
        log_to_ui_error("获取已转测需求或即将转测需求失败")

    return last_week_testing_task,tested_or_testing_req


def get_fixed_bug_list(name_value, time_value):
    '''
    获取修复bug
    '''
    excel_data = get_excel_data()
    url = "https://www.tapd.cn/api/search_filter/search_filter/search"
    
    # 构建搜索数据字典
    search_data_dict = {
        "data": [
            {
                "fieldOption": "in",
                "fieldType": "user_chooser",
                "entity": "bug",
                "fieldSubValue": "",
                "fieldSystemName": "te",
                "fieldDisplayName": "测试人员",
                "selectOption": [],
                "value": f"{name_value};",
                "fieldIsSystem": "1",
                "id": "2"
            },
            {
                "id": "6",
                "fieldLabel": "状态",
                "fieldOption": "in",
                "fieldType": "multi_select",
                "fieldSystemName": "status",
                "value": "Beta已通过|alpha已通过|已修复上线|用户数据已修复",
                "fieldIsSystem": "1",
                "entity": "bug"
            },
            {
                "id": "7",
                "fieldLabel": "预计结束",
                "fieldOption": "between",
                "fieldType": "dateinput",
                "fieldSystemName": "due",
                "value": f"{time_value}",
                "fieldIsSystem": "1",
                "entity": "bug"
            }
        ],
        "optionType": "AND",
        "needInit": "1"
    }
    
    # 将搜索数据字典转换为JSON字符串
    search_data_json = json.dumps(search_data_dict)
    
    # 构建完整的payload
    payload_dict = {
        "workspace_ids": f"{excel_data['项目ID']}",
        "search_data": search_data_json,
        "obj_type": "bug",
        "search_type": "advanced",
        "page": 1,
        "perpage": "100",
        "block_size": 50,
        "parallel_token": "",
        "order_field": "created",
        "order_value": "desc",
        "show_fields": [],
        "extra_fields": [],
        "display_mode": "list",
        "version": "1.1.0",
        "only_gen_token": 0,
        "exclude_workspace_configs": [],
        "from_pro_dashboard": 1,
        "dsc_token": "ZYJtvBRTRbQCNOMH"
    }
    
    # 将payload字典转换为JSON字符串
    payload = json.dumps(payload_dict)
    headers = {
    'authority': 'www.tapd.cn',
    'accept': 'application/json, text/plain, */*',
    'accept-language': 'zh-CN,zh;q=0.9',
    'content-type': 'application/json',
    'cookie': excel_data['Cookie'],
    'origin': 'https://www.tapd.cn',
    'referer': 'https://www.tapd.cn/tapd_fe/worktable/search?queryToken=681dd83855b5148bfb7599c5ef1d08d7',
    'sec-ch-ua': '"Not)A;Brand";v="24", "Chromium";v="116"',
    'sec-ch-ua-mobile': '?0',
    'sec-ch-ua-platform': '"Windows"',
    'sec-fetch-dest': 'empty',
    'sec-fetch-mode': 'cors',
    'sec-fetch-site': 'same-origin',
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.5845.97 Safari/537.36 Core/1.116.562.400 QQBrowser/19.6.6725.400'
    }

    # 初始化任务计数器和结果字符串
    task_count = 0
    last_week_bug_fix = 'BugFix:\n'
    
    respose_code,response = api_request(method="POST", url=url, headers=headers, data=payload)
    if respose_code == 200 and response["data"]['list'] != []:
        try:
            bugs_list = response["data"]['list']
            logger.info(f"修复的Bug列表: {bugs_list}")
            for bug in bugs_list:
                bug_name = bug["title"]
                task_count += 1
                last_week_bug_fix += f"\t{task_count}. {bug_name}\n"
        except Exception as e:
            logger.error(f"获取数据失败: {str(e)}")
            log_to_ui_error(f"获取数据失败: {str(e)}")
    elif respose_code == 200 and response["data"]['list'] == []:
        logger.info(f"{time_value}期间没有修复的Bug")
        log_to_ui_info(f"{time_value}期间没有修复的Bug")
    elif respose_code != 200:
        logger.error("获取修复的Bug失败")
        log_to_ui_error("获取修复的Bug失败")
    else:
        logger.error(f"请求异常，状态码: {respose_code}")
        log_to_ui_error(f"请求异常，状态码: {respose_code}")
    return last_week_bug_fix

if __name__ == '__main__':
    testing_meeting(name_value="陈昌松",time_value="2025-10-01 00:00,2025-10-01 23:59")
